import { createApp } from 'vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'; 
import zhCn  from 'element-plus/es/locale/lang/zh-cn'; 
import * as ElementPlusIconsVue from '@element-plus/icons-vue';
import App from './App.vue';
import router from './router';
import axios from 'axios';
import Particles from '@tsparticles/vue3';
import { loadSlim } from '@tsparticles/slim';
import 'virtual:svg-icons-register'; // 注册 SVG 图标
import SvgIcon from './components/SvgIcon'; // 导入 SvgIcon 组件
import './styles/index.scss' // global css
import { LoginEmployee,connrequest } from './api/connrequest'

const app = createApp(App);
app.component('svg-icon', SvgIcon); // 全局注册 SvgIcon 组件

async function fetchData() {
  try {
    const response = await axios.get('config.json');
    const jsonData = response.data;
    return jsonData.pageTitle;
  } catch (error) {
    console.error('Error fetching config.json:', error);
    return null;
  }
}

router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  try {
    const title = await fetchData() || 'AI管理系统';
    document.title = title;
  } catch (error) {
    console.error('Error setting title:', error);
    document.title = 'AI管理系统';
  }

  // 检查是否已登录
  const token = sessionStorage.getItem('gptToken');
  if (!token) {
    // 未登录，尝试自动登录
    const { userid, pwd } = to.query;
    if (userid && pwd) {
      try {
        const data = {
          Data: {
            UserID: btoa(userid),
            Password: btoa(pwd)
          }
        };
        const res = await LoginEmployee(data);

        if (res.Status.StatusCode === 0) {
          sessionStorage.setItem('userName', userid);
          sessionStorage.setItem('gptToken', res.Token);
          sessionStorage.setItem('Name', res.Data.Name);
          sessionStorage.setItem('AiMode', JSON.stringify(res.Data.AiMode));
          sessionStorage.setItem('AiTimeOut', res.Data.AiTimeOut);
          sessionStorage.setItem('RightAI', res.Data.RightAI);

          try {
            const res = await connrequest('GetUserPreference');
            const data = res?.Data?.GPT?.isNightMode ? res.Data.GPT.isNightMode : 'night';
            localStorage.setItem('isNightMode', data);
          } catch (error) {
            console.log('获取主题数据失败', error);
          }

          // 避免无限重定向
          if (to.path !== '/AI/chat') {
            next('/AI/chat');
          } else {
            next();
          }
        } else {
          // 登录失败，传递错误信息
          next({
            path: '/',
            query: { error: encodeURIComponent(res.Status.Msg2Client), redirect: to.fullPath }
          });
        }
      } catch (error) {
        console.error('自动登录失败:', error);
        const errorMessage = error.response?.data?.Status?.Msg2Client || '用户名或密码错误';
        next({
          path: '/',
          query: { error: encodeURIComponent(errorMessage), redirect: to.fullPath }
        });
      }
    } else {
      // 无查询参数，重定向到登录页面
      if (to.path !== '/') {
        next({ path: '/', query: { redirect: to.fullPath } });
      } else {
        next();
      }
    }
  } else {
      next();
  }
});

app.use(ElementPlus, { locale: zhCn });
app.use(router);
app.use(Particles, {
  init: async (engine) => {
    await loadSlim(engine);
  },
});
app.config.globalProperties.$http = axios;
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}

app.mount('#app');